﻿/* 插件说明：Cookie plugin
*编写:justkeepmoving,
QQ:408720988,
Bug报告请加QQ或者发关邮件到QQ邮箱,谢谢
*1、本插件支持多种操作Cookie有模式。
*让cookie存的值更加多样化，方便操作。
*2、本插件支持多种格式的添加，修改cookie的方式，
*具体请看如下
1.
①$.SetCookie("TestCookie","testvalue"),②$.SetCookie("TestCookie","testvalue",{expires:5});
操作结果：
①为创建一个名为TestCookie的cookie，其值是testvalue,有效期为关闭浏览器后消失；
②为创建一个名为TestCookie的cookie，其值是testvalue,有效期5天，
注意：cookie实际存储格式为：name=TestCookie[{"TestCookie":"testvalue"}]

获取：如果要获取此cookie的值,var returnvalue=$.GetCookie("TestCookie"),
注意：这返回的不是实际的值，而是以JSON格式返回的的JSON数据
即[{"TestCookie":"testvalue"}]可以用returnvalue[0].TestCookie来获得其值testvalue;或者用$.GetCookie("TestCookie","TestCookie")
即可获得值testvalue，注：后面的TestCookie是在未指定子键名的默认名，即默认子键名与Cookie名相同。

修改：如果要修改此Cookie,用  
①:$.UpdateCookie("TestCookie","NewValue")，②:$.UpdateCookie("TestCookie",null) ③:$.UpdateCookie("TestCookie",{expires:8});
①是修改cookie的值，②第二个是让cookie失效，即设置后cookie失效。③最后一个是修改cookie的有效期为8天。

2.$.SetCookie("TestCookie",{"KeyValues":"'Key1':'value1','Key2':'value2'"},{expires:4});
需要注意的是：前面的KeyValues为不能更改的，这个是固定格式。即在需要存储值对的数据时，格式必须如此，如果存储单一的值用第一种
方式即可。后面的即'Key1':'value1','Key2':'value2'为实际的存储值。
比如可以设置成'username':'testUser','passoword':'123445'来记录用户的登录情况，注意完整格式为
$.SetCookie("UserCookie",{"KeyValues":"'username':'testUser','passoword':'123445'"},{expires:4});
{expires:4}这个参数可选填。实际存储值为：[{'Key1':'value1','Key2':'value2'}]

获取：此处分情况讨论：①$.GetCookie("TestCookie")②$.GetCookie("TestCookie","Key1");③$.GetCookie("TestCookie","Key1",0)
解释：①是获取TestCookie的值的JSON格式，结果为var result=[{'Key1':'value1','Key2':'value2'}},可以用result[0].Key1得到value1
②是直接获取的是TestCookie这个Cookie中子键（这里的子键是我定义的，有点不好理解，可以不用看前面的KeyValues，后面的实际上是键值对方式）Key1的值的组合这里其实只有一个键为Key1的，③是直接获取第一个 key1的值，和result[0].Key1这个操作结果一致
修改： $.UpdateCookie("TestCookie","key1","newvalue");修改key1的值,
*
*3.$.SetCookie("TestCookie",[{"KeyValues":"'Key1':'value1','Key2':'value2'"},{{"KeyValues":"'Key1':'value11','Key2':'value22'"}}],{expires:4});

获取：①var result=$.GetCookie("TestCookie","Key1")，这是返回由Key1组成的JSON数据，值为[{'key1':'value1'},{'key1':'value11'}],
*可以用result[0].key1或者result[1].key1分别获取value1和value11
*②var result=$.GetCookie("TestCookie","Key1",0)直接返回value1，$.GetCookie("TestCookie","Key1",1)返回value11
*修改：   $.UpdateCookie("TestCookie","key1","newvaluw",0);修改后，第一个key1值为newvalue,如果把0换成1，则第二个key1值为newvalue.$.UpdateCookie("TestCookie",{expires:5});修改有效期为5天，$.UpdateCookie("TestCookie",null);删除cookie，
* */

//输入格式支持
//格式一：("cookiename","cookievalue"),
//格式二：("cookiename",{"KeysValues":"key1:value1,key2:value2"},{expires:7})
//格式三：("cookiename", [{ "KeysValues": "key1:value1,key2:value2" },{ "KeysValues": "key1:value2,key2:value3" }],{expires:7})
jQuery.SetCookie = function (CookieName, options, CookieSetttings) {
    var path, domain, secure;
    if (typeof CookieSetttings != "undefined") {
        options = options || {};
        if (options == null)//
            CookieSetttings.expires = -1;
        var expires = '';
        if (CookieSetttings.expires && (typeof CookieSetttings.expires == 'number' || CookieSetttings.expires.toUTCString)) {
            var date;
            if (typeof CookieSetttings.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (CookieSetttings.expires * 24 * 60 * 60 * 1000));
            } else {
                date = CookieSetttings.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        path = CookieSetttings.path ? '; path=' + CookieSetttings.path : '';
        domain = CookieSetttings.domain ? '; domain=' + CookieSetttings.domain : '';
        secure = CookieSetttings.secure ? '; secure' : '';
    }
    var cookievalue = "[{";
    if (options !== null) {
        if (typeof options == "object")//确定输入格式不是格式一
        {
            if (typeof options.length != "undefined") {//确定输入格式是格式三
                for (var i = 0; i < options.length; i++) {
                    if (i != options.length - 1) {
                        cookievalue += options[i].KeyValues + "},{";
                    }
                    else {
                        cookievalue += options[i].KeyValues + "}]";
                    }
                }
            }
            else {
                cookievalue = "[{" + options.KeyValues + "}]"; //确定输入格式是格式二
            }
        }
        else {
            //确定输入格式是格式一
            cookievalue = "[{'" + CookieName + "':'" + options + "'}]";
        }
    }
    else {
        cookievalue += "}]";
    }
    document.cookie = [CookieName, '=', encodeURIComponent(cookievalue), expires, path, domain, secure].join('');
}
jQuery.GetCookie = function (CookieName, KeyName, index) {
    var cookieValue = GetCookieByName(CookieName);
    var EvalResult = eval("(" + cookieValue + ")"); //转化为JSON格式
    if (cookieValue === null)
        return "NoSuchCookie"; //不存在此cookie
    //给出了访问索引
    if (typeof index == "number") {
        if (index >= EvalResult.length) {
            return "OutOfRange"; //超出索引范围
        }
        cookieValue += "[" + index + "].";
    }
    var ReturnJson = "[";
    var temValue = "";
    if (typeof KeyName != "undefined") {
        if (typeof index != "number") {
            for (var i = 0; i < EvalResult.length; i++) {
                temValue += "{\"";
                for (var j in EvalResult[i]) {
                    if (j == KeyName) {
                        temValue += j + "\":\"" + EvalResult[i][j] + "\",";
                    }
                }
                temValue = temValue.substring(0, temValue.length - 1);
                temValue += "}";
                if (temValue.length > 2) {
                    ReturnJson += temValue + ",";
                    temValue = "";
                }
                if (i == EvalResult.length - 1) {
                    ReturnJson = ReturnJson.substring(0, ReturnJson.length - 1) + "]";
                }

            }
            return eval("(" + ReturnJson + ")");
        }
        else {
            return eval("(" + cookieValue + KeyName + ")");
        }
    }
    else {
        return EvalResult;
    }
}
//修改cookie值
//支持修改方式为
//格式一：(cookiename,KeyName,Index);
//格式二：（cookiename,{expires:6});
jQuery.UpdateCookie = function (CookieName, KeyName, KeyValue, index, options) {
    var CookieValue = GetCookieByName(CookieName);
    if (KeyName === null) {
        options = { expires: -1 };
    }
    else if (typeof KeyName == "object") {
        options = KeyName;
    }
    if (typeof KeyValue == "undefined")//此时修改的 cookie格式为：（cookiename,value）产生的
    {
        KeyValue = KeyName;
        KeyName = CookieName;
    }
    else if (typeof KeyValue == "object") {
        options = KeyValue;
        KeyValue = KeyName;
        KeyName = CookieName;
    }
    var path, domain, secure;
    var ChangeIndex = 0;
    var EvalResult;
    if (CookieValue === null)
        return "NoSuchCookie"; //不存在此cookie 
    EvalResult = eval("(" + CookieValue + ")");
    if ((typeof index == "number")) { //如果未给出了修改的索引，默认为0 
        if (index >= EvalResult.length) {
            return "OutOfRange"; //超出索引范围
        }
        ChangeIndex = index;
    }
    else if (typeof index == "object") { //如果给出的参数是1，2，3，5
        options = index;
        options = options || {};
        if (options == null)
            options.expires = -1;
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof CookieSetttings.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
    }

    //遍历修改
    var NewValue = "[{";
    if (ChangeIndex > EvalResult.length) {
        return "OutOfRange"; //超出索引范围
    }
    for (var j = 0; j < EvalResult.length; j++) {
        NewValue += "\"KeyValues\":\"";
        for (var i in EvalResult[j]) {
            if (i == KeyName && j == ChangeIndex) {
                NewValue += "'" + i + "':'" + KeyValue + "',";
            }
            else {
                NewValue += "'" + i + "':'" + EvalResult[j][i] + "',";
            }
        }
        NewValue = NewValue.substring(0, NewValue.length - 1);
        if (j != EvalResult.length - 1) {
            NewValue += "\"},{";
        }
        else {
            NewValue += "\"}]";
        }
    }
    //重新设置cookie参数
    jQuery.SetCookie(CookieName, eval("(" + NewValue + ")"), options);
}
//根据Cookie名称获取Cookie值
function GetCookieByName(CookieName) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, CookieName.length + 1) == (CookieName + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(CookieName.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}